﻿using HLStock.MyExcep;

namespace HLStock.Common
{
    public static class ServiceLoader
    {
        public static void InitInstance(IServiceProvider instance)
        {
            if (instance == null)
                throw new MyEmptyOrNullDataException();
            Instance = instance;
        }
        internal static IServiceProvider? Instance { get; private set; }
        public static T GetService<T>()
        {
            var serviceProvider = Instance!.GetRequiredService<IHttpContextAccessor>()?
                .HttpContext?.RequestServices;
            if (serviceProvider == null)
                throw new MyCreatClassFailedException(typeof(T));
            try
            {
                return serviceProvider.GetService<T>()!;
            }
            catch (Exception ex)
            {
                MyLogger.Err(ExceptionUtil.FormatExceptionInfo(ex));
                throw new MyCreatClassFailedException(typeof(T));
            }
        }
        public static HttpContext GetHttpContext()
        {
            try
            {
                var httpContext = Instance!.GetRequiredService<IHttpContextAccessor>().HttpContext;
                return httpContext;
            }
            catch (Exception ex)
            {
                MyLogger.Err(ExceptionUtil.FormatExceptionInfo(ex));
                throw new MyCreatClassFailedException(typeof(IHttpContextAccessor));
            }
        }
    }
}
